<%@ page import="com.itqn.pojo.Category" %>
<%@ page import="com.itqn.service.CategoryService" %>
<%@ page import="com.itqn.service.Impl.CategoryServiceImpl" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/style/common.css">
    <link rel="stylesheet" type="text/css" href="//at.alicdn.com/t/c/font_4586065_zr0eqag50cb.css">
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/style/product.css">
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/style/page.css">
</head>
<body>
<c:import url="header.jsp"></c:import>
<%
    CategoryService categoryService = new CategoryServiceImpl();
    List<Category> categoryList = categoryService.findAllCategory();
    request.setAttribute("categoryList", categoryList);
%>
<div class="right">
    <div class="content">
        <div class="tablesearch">
            <label class="name">商品名称:</label>
            <input type="text" class="productName" id="name" placeholder="请填写商品名称">
            <label class="classify">商品分类:</label>
            <select class="categoryId" id="categoryId">
                <option value="-1">请选择</option>
                <c:forEach items="${requestScope.categoryList}" var="i">
                    <option value="${i.id}">${i.name}</option>
                </c:forEach>
            </select>
            <label class="status">售卖状态:</label>
            <select id="status">
                <option value="-1">请选择</option>
                <option value="1">起售</option>
                <option value="0">停售</option>
            </select>
            <input type="button" value="查询" onclick="bind()" class="btn"/>
            <div class="deleteinbatches">
                <span onclick="deleteAll()">批量删除</span>
                <button id="addbtn" onclick="add()">
                    +添加商品
                </button>
            </div>
        </div>
        <form method="post" accept-charset="UTF-8">
            <table cellspacing="0" id="tb">
                <thead>
                <tr>
                    <th></th>
                    <th>商品名称</th>
                    <th>图片</th>
                    <th>商品分类</th>
                    <th>售价</th>
                    <th>售卖状态</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody></tbody>
            </table>
            <div class="divpage">

                <span class="sum"></span>
                <select class="pageselect">
                    <option>2条/页</option>
                    <option>3条/页</option>
                    <option>5条/页</option>
                    <option>10条/页</option>
                </select>
                <div class="prev" style="display: inline-block">
                    <i class="iconfont icon-shangyiyeqianyiye"></i>
                </div>
                <span class="skipPage">
                </span>
                <div class="next" style="display: inline-block">
                    <i class="iconfont icon-xiayiyehouyiye"></i>
                </div>
                <span class="leavefor">
                前往
                <input type="text" class="el-input__inner">
                页
                </span>
            </div>
        </form>
    </div>
</div>
<c:import url="Leftnavigationbar.jsp"></c:import>
<script src="${pageContext.request.contextPath}/js/jquery.js"></script>
<script>
    const page = {
        pageSize: 5,
        page: 1
    }

    $(function () {
        bind()
    })

    let pageCount = 0

    function bind() {
        $.ajax({
            type: 'post',
            url: '/productQuery?',
            data: {
                page: page.page,
                pageSize: page.pageSize,
                name: $('.productName').val(),
                categoryId: $('.categoryId').val(),
                status: $('#status').val()
            },
            success: function (data) {
                data = JSON.parse(data)
                if (!data.pageCount) {
                    document.querySelector('form').style.display = 'none'
                    return document.querySelector('.divpage').style.display = 'none'
                }
                document.querySelector('form').style.display = 'inline-block'
                document.querySelector('.divpage').style.display = 'block'
                // 渲染分页部分
                document.querySelector('.sum').innerHTML = '共 ' + data.pageCount + ' 页'

                document.querySelector('.skipPage').innerHTML = page.page

                document.querySelector('tbody').innerHTML = data.list.map(item => `
                <tr>
                    <td>
                        <input type="checkbox" value=" ` + item.id + `"/>
                    </td>
                    <td>` + item.name + `</td>
                    <td><img src='` + item.image + `' width=40 height=40></td>
                    <td>` + item.category.name + `</td>
                    <td>￥` + item.price + `</td>
                    <td><p class="` + (item.status === 1 ? "enable" : "disable") + `"></p>` + (item.status === 1 ? "起售" : "停售") + `</td>
                    <td>
                        <a href="/productEchoServlet?id=` + item.id + `">修改</a>
                        <a onclick="del(` + item.id + `)">删除</a>
                        <a href="#" class="`+(item.status === 0 ? "statusEnable" : "statusDisable")+`" onclick="updateStatus(`+item.id+`, `+item.status+`)">`+(item.status === 0 ? "启用" : "禁用")+`</a>
                    </td>
                </tr>`).join('')
                const ops = document.querySelectorAll('.pageselect option');
                for (const op of ops) {
                    if (op.innerHTML.includes(page.pageSize)) op.selected = "selected"
                }
                pageCount = data.pageCount
                if (page.page <= 1) {
                    document.querySelector('.prev').classList.add('pageDisabled')
                } else {
                    document.querySelector('.prev').classList.remove('pageDisabled')
                }
                if (page.page >= pageCount) {
                    document.querySelector('.next').classList.add('pageDisabled')
                } else {
                    document.querySelector('.next').classList.remove('pageDisabled')
                }
                document.querySelector('.el-input__inner').value = page.page
            }
        })
    }

    document.querySelector('.pageselect').addEventListener('change', e => {
        page.page = 1
        page.pageSize = e.target.value.substring(0, e.target.value.indexOf('条'))
        bind()
    })
    document.querySelector('.prev').addEventListener('click', e => {
        if (page.page === 1) return
        document.querySelector('.next').classList.remove('pageDisabled')
        page.page--
        bind()
    })

    document.querySelector('.next').addEventListener('click', e => {
        if (page.page >= pageCount) return
            document.querySelector('.prev').classList.remove('pageDisabled')
        if (page.page === pageCount - 1) {
            document.querySelector('.next').classList.add('pageDisabled')
        }
        page.page++
        bind()
    })
    document.querySelector('.el-input__inner').addEventListener('blur', e => {
        if (e.target.value > pageCount || e.target.value < 1) {
            return
        }
        page.page = e.target.value
        bind()
    })

    function del(id) {
        if (confirm('您确定要删除这条数据吗?', '提示')) {
            $.ajax({
                type: 'post',
                url: '/ProductDeleteServlet',
                data: {id},
                success: function (data) {
                    if (data === 'ok') {
                        if (page.page > 1 && document.querySelectorAll('tbody tr').length === 1) {
                            page.page--
                        }
                        bind()
                    }
                }
            })
        }
    }

    function deleteAll() {
        var allI = document.querySelectorAll('input[type=checkbox]:checked');
        var str = "";
        for (var i = 0; i < allI.length; i++) {
            if (i == allI.length - 1) {
                str += allI[i].value
            } else {
                str += allI[i].value + ","
            }
        }
        //跳转
        window.location = "/ProductDeleteAllServlet?key=" + str;
    }

    function update(id) {
        window.location.href = '/admin/product/update.jsp?id=' + id;
    }

    const updateStatus = (id, status) => {
        $.ajax({
            type: 'get',
            url: '/productStatus',
            data: {
                id,
                status: status === 1 ? 0 : 1
            },
            success: function (data) {
                bind()
            }
        })
    }
    const btn = document.querySelector('.btn')
    btn.addEventListener('mouseenter', function () {
        btn.style.backgroundColor = '#999999'
    })
    btn.addEventListener('mouseleave', function () {
        btn.style.backgroundColor = ''
    })
    document.querySelector('#addbtn').addEventListener('mouseenter', function () {
        const addbtn = document.querySelector('#addbtn')
        addbtn.style.backgroundColor = 'rgba(168, 240, 135,0.7)'
    })
    document.querySelector('#addbtn').addEventListener('mouseleave', function () {
        const addbtn = document.querySelector('#addbtn')
        addbtn.style.backgroundColor = ''
    })
    document.querySelector('.pageselect').addEventListener('mouseenter', function () {
        var pageselect = document.querySelector('.pageselect')
        pageselect.style.borderColor = 'rgb(168,240,135)'
    })
    document.querySelector('.pageselect').addEventListener('mouseleave', function () {
        var pageselect = document.querySelector('.pageselect')
        pageselect.style.borderColor = ''
    })
    const inputall = document.querySelectorAll('.productName')
    for (let i = 0; i < inputall.length; i++) {
        inputall[i].addEventListener('focus', function () {
            inputall[i].style.outline = 'none'
            inputall[i].style.border = '1px solid rgb(168, 240, 135)'
        })
    }
    for (let i = 0; i < inputall.length; i++) {
        inputall[i].addEventListener('blur', function () {
            inputall[i].style.outline = 'none'
            inputall[i].style.border = ''
        })
    }

    function add() {
        location.href = '/admin/product/add.jsp'
    }
</script>
</body>
</html>